package com.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lulei
 * @date 2020年12月25日 14:25:51
 */
public class RequestProcessor implements Runnable{
    private Socket socket;
    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();
    private Mapper mapper;
    public RequestProcessor(Socket socket,Mapper mapper){
        this.mapper = mapper;
        this.socket = socket;
    }


    @Override
    public void run() {

        try {
            //获取请求信息输入流
            InputStream inputStream = this.socket.getInputStream();
            Request request = new Request(inputStream);
            System.out.println("请求信息："+request.getReqcontent());
            String ouputStr = "Hello Mycat !";
            OutputStream outputStream = this.socket.getOutputStream();//获取输出流
            Responese responese = new Responese(outputStream);
            
            HttpServlet httpServlet =  getHttpServelet(request);
            if(httpServlet != null){
                httpServlet.Service(request,responese);

            }else{
                responese.outpuFile(request.getUrl());
            }
            this.socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private HttpServlet getHttpServelet(Request request) {
        String host = request.getHost();
        String appName = request.getAppName();
        String partUrl = request.getPartUrl();
        List<Host> host1 = this.mapper.getHost();
        List<AppContext> context = null;
        List<WrapServlet> wrapServlets = null;
        for (Host host2 : host1) {
            if(host2.getHostname().equals(host)){
               context = host2.getContext();
               break;
            }
        }
        if(context != null){
            for (AppContext appContext : context) {
                if(appName.equals(appContext.getAppName())){
                    wrapServlets = appContext.getWrapServlets();
                    break;
                }
            }
        }
        if(wrapServlets != null){
            for (WrapServlet wrapServlet : wrapServlets) {
                if(partUrl.equals(wrapServlet.getUrl())){
                    return (HttpServlet) wrapServlet.getServlet();
                }
            }
        }
        return null;
    }
}
